package cn.edu.zut.salarymanagesystem.utils;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.activities.MainActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

@SuppressWarnings("deprecation")
public class DownloadTask extends AsyncTask<ProgressDialog, Integer, String> {
    private String url = null;
    @SuppressLint("StaticFieldLeak")
    private Context context = null;
    private ProgressDialog progressDialog = null;
    private String fileLocation = null;


    /**
     * @deprecated
     */
    public DownloadTask(String url, Context context) {
        super();
        this.context = context;
        this.url = url;
    }

    /**
     * @deprecated
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.fileLocation = context.getFilesDir() + "/latest.apk";
        Log.i("d8g", "fileLocation:" + fileLocation);
        // 使用实例变量 progressDialog，而不是在方法内部创建一个新的局部变量
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.setIndeterminate(false);
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setTitle("版本升级");
        progressDialog.setMessage("下载中，请稍后...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }


    /**
     * @param string
     * @deprecated
     */
    @Override
    protected void onPostExecute(String string) {
        super.onPostExecute(string);
        progressDialog.dismiss();
        if (string != null) {
            openAPK();
        } else {
            Toast.makeText(context, "下载失败！服务器出现故障！请重新进入并选择取消按钮！", Toast.LENGTH_LONG).show();
            ((MainActivity) context).finish();
        }
    }

    /**
     * @param values
     * @deprecated
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        this.progressDialog.setProgress(values[0]);
    }

    /**
     * @param aString
     * @deprecated
     */
    @Override
    protected void onCancelled(String aString) {
        super.onCancelled(aString);
    }

    /**
     * @deprecated
     */
    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    /**
     * @param dialogs
     * @deprecated
     */
    @Override
    protected String doInBackground(ProgressDialog... dialogs) {
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Log.i("d8g", "About to execute request");
            Response response = client.newCall(request).execute();
            // 检查响应是否成功
            if (!response.isSuccessful()) {
                Log.e("d8g", "服务器返回不成功！");
                return null;
            }
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                Log.e("d8g", "responseBody 为空！");
                return null;
            }
            long fileLength = responseBody.contentLength();
            Log.i("d8g", "File length: " + fileLength);
            InputStream inputStream = responseBody.byteStream();
            OutputStream outputStream = new FileOutputStream(fileLocation);

            byte[] buffer = new byte[4096];
            long totalBytesRead = 0;
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                publishProgress((int) (totalBytesRead * 100 / fileLength));
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return fileLocation;

        } catch (IOException e) {
            Log.e("d8g", "Download error :" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public void openAPK() {
        Uri apkUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", new File(fileLocation));
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resolveInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        context.startActivity(intent);
    }

}
